<?php
namespace app\backend\controller;

use app\backend\model\AuthAccess;
use app\backend\model\Account as AccountModel;
use think\Db;
use think\Request;

/**
 * 登录控制器
 * @package app\backend\controller
 */
class Login extends \think\Controller
{
    // 登录页面
    public function index()
    {
        return $this->fetch();
    }

    // 执行登录
    public function login()
    {
        $req = \think\Request::instance();
        if ($req->isPost())
        {
            $username = $req->post('username');
            $password = md5($req->post('password'));

            $remember = $req->post('remember');

            $record = \think\Db::name('account')->where(['username' => $username])->find();
            //$account_id = $record['account_id'];
            //var_dump($password);
            if (!$record || ($record['password'] != $password))
            {
                //var_dump($record['password']);exit;
                $this->error('用户名或者密码错误，请检查');
            }
            if ($remember)
            {
                \think\Cookie::set('username', $username, 86400);
            }
            \think\Session::set('login_user', $username);
            \think\Session::set('login_id', $record['account_id']);
            \think\Session::set('auth', $record['auth']);
            //AuthAccess::access2Session($account_id);
            $this->redirect('backend/index/index');
        }
    }

    // 退出
    public function logout()
    {
        \think\Session::clear();
        \think\Cookie::delete('username');
        $this->redirect('index');
    }

    public function resetpass(){
        $req = \think\Request::instance();
        if ($req->isPost())
        {
            $username = $req->post('username');
            $password = md5($req->post('password'));
            $pass1 = ($req->post('password1'));
            if(empty($pass1)){
                $this->error("密码不能为空");
            }
            $password1 = md5($req->post('password1'));
            $password2 = md5($req->post('password2'));
            $userpd2 = AccountModel::where(["account_id"=>2])->value("password");
            /*print_r($password);
            echo "<br>";
            print_r($userpd2);exit;*/
            if(!($password == $userpd2)){
                $this->error("原始密码输入错误");
            }
            if($password1 != $password2){
                $this->error("重置密码输入错误");
            }

            $user = \think\Db::name('account')->where(["account_id"=>2])->update(['username' => $username]);
            $pass = \think\Db::name('account')->where(["account_id"=>2])->update(['password' => $password1]);
            $this->success('修改成功',url('login/index'));
        }

        $model = new AccountModel;
        $pass = $model->getAll();
        //var_dump($pass);exit;
        $this->assign('user',$pass[0]);
        return $this->fetch();
    }
}